/*
 * https://github.com/baryon/tracer
 * @useage: 
 *  
 *  export LOG_PATH=/data/logs/boss/crm
 *
 *  var logger = require('../lib/logger').logger();
 *
 *  logger.log('hello');
 *  logger.trace('hello', 'world');
 *  logger.debug('hello %s', 'world', 123);
 *  logger.info('hello %s %d', 'world', 123, {foo : 'bar'});
 *  logger.warn('hello %s %d %j', 'world', 123, {foo : 'bar'});
 *  logger.error('hello %s %d %j', 'world', 123, {foo : 'bar'}, [ 1, 2, 3, 4 ], Object);
 *
 * */


var fs = require('fs');
var tracer = require('tracer');
var logger = null;

function create(){
    if(!logger){
        var path = process.env.LOG_PATH || '.';
        var debugLogPath = path + '/debug.log';
        var errorLogPath = path + '/error.log';
        logger = tracer.console({
            transport : function(data) {
                switch( data.level ){
                case 4:
                case 5:
                    fs.appendFile( errorLogPath , data.output + '\n', (err) => {
                        if (err) throw err;
                    });
                default:
                    fs.appendFile( debugLogPath , data.output + '\n', (err) => {
                        if (err) throw err;
                    });
                }
            }
        });
        if( process.env.NODE_ENV =='production' ){
            tracer.setLevel( 'info' );
        }
    }
    return logger;
}

process.on('SIGPIPE', function(){   
    // logrotate , reset log writeStream if we were useing fs.writeStream.
});

exports.logger = create;
